/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nmp.common;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class RestUtil {

    private static final Logger logger = Logger.getLogger(RestUtil.class);

    public static Map<String, String> httpsRest(String restUrl) {
        try {
            Map<String, String> data = new HashMap<>();
            URL url = new URL(restUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//            connection.setRequestMethod("GET");
//            connection.setUseCaches(false);
//            connection.setDoInput(true);
            connection.setDoOutput(true);
//            connection.setReadTimeout(10000);
//            connection.setConnectTimeout(10000);
//            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
//                wr.flush();
//            }
            //Get Response
            int respCode = connection.getResponseCode();
            data.put("respCode", String.valueOf(respCode));
            data.put("respMsg", connection.getResponseMessage());

            try (InputStream is = connection.getInputStream()){
                StringBuilder response;
                try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
                    String line;
                    response = new StringBuilder();
                    while ((line = rd.readLine()) != null) {
                        response.append(line);
                        response.append('\r');
                    }
                    data.put("data", response.toString());
                    rd.close();
                }
                is.close();
            }
            return data;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

}
